package com.fjsaas.flyway.command;

import java.io.File;
import java.util.Date;
import java.util.Map; 

import com.fjsaas.flyway.backup.MysqlBackup;
import com.fjsaas.web.utils.MyUtil;

public class MysqlBackupCommand implements Command {

	private MysqlBackup mysqlBackup;
	
	private String username;
	private String password;
	private String charset = "UTF-8";
	private String jdbcUrl;	
	private String destDir;
	

	@Override
	public void execute() {
		Map<String, String> map = MyUtil.parseJdbcUrl(jdbcUrl);
		String jdbcUrl = map.get("jdbcUrl");
		String host = map.get("host");
		String schema = map.get("dbName");
		
		String year = MyUtil.get_YYYY();
		String month = MyUtil.get_MM();
		String day = MyUtil.get_DD();
		String tmpDir = destDir + File.separatorChar + year + File.separatorChar + month + File.separatorChar;
		String filename = "db" + MyUtil.getFullDateStr(new Date()) + ".sql"; 
		File file = new File(tmpDir);
		if(!file.exists()){
			file.mkdirs();
		}
		
		mysqlBackup.setUsername(username);
		mysqlBackup.setPassword(password);
		mysqlBackup.setCharset(charset);
		mysqlBackup.setHost(host);
		mysqlBackup.setDbName(schema);
		mysqlBackup.setDest(tmpDir + filename);
		mysqlBackup.backup();
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getCharset() {
		return charset;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}
	
	public MysqlBackup getMysqlBackup() {
		return mysqlBackup;
	}

	public void setMysqlBackup(MysqlBackup mysqlBackup) {
		this.mysqlBackup = mysqlBackup;
	}

	public String getJdbcUrl() {
		return jdbcUrl;
	}

	public void setJdbcUrl(String jdbcUrl) {
		this.jdbcUrl = jdbcUrl;
	}

	public String getDestDir() {
		return destDir;
	}

	public void setDestDir(String destDir) {
		this.destDir = destDir;
	}

}
